package com.exampl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.exampl.common.R;
import com.exampl.domain.AddressBook;
import com.exampl.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    HttpSession session;

    // 查找用户的所有地址
    @GetMapping("/list")
    public R<List<AddressBook>> listR(){
        // 获取当前用户id
        Long id = (Long) session.getAttribute("user");
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<AddressBook>();
        lqw.eq(AddressBook::getUserId, id);
        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);
    }

    //新增地址
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        // 获取当前用户id
        Long id = (Long) session.getAttribute("user");
        addressBook.setUserId(id);
        addressBookService.save(addressBook);
        return R.success("添加成功！");
    }

    // 修改地址
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功!");
    }

    // 查询单个地址
    @GetMapping("/{id}")
    public R<AddressBook> getOne(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        return R.success(addressBook);
    }

    // 删除地址
    @DeleteMapping
    public R<String> delete(Long ids){
        addressBookService.removeById(ids);
        return R.success("删除成功!");
    }

    // 修改默认地址
    @PutMapping("/default")
    public R<String> toDefault(@RequestBody AddressBook addressBook){
        // 获取当前用户id
        Long user_id = (Long) session.getAttribute("user");
        // 先将默认地址取消
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<AddressBook>();
        lqw.eq(AddressBook::getUserId, user_id);
        lqw.eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressBookService.getOne(lqw);
        if(one != null){
            one.setIsDefault(0);
            addressBookService.updateById(one);
        }
        // 将需要该默认的修改
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success("修改成功！");
    }

    // 获取默认地址
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        // 获取当前用户id
        Long user_id = (Long) session.getAttribute("user");
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<AddressBook>();
        lqw.eq(AddressBook::getIsDefault, 1);
        lqw.eq(AddressBook::getUserId, user_id);
        AddressBook one = addressBookService.getOne(lqw);
        return R.success(one);
    }
}
